#!/usr/bin/env bash

include() {
    if [ ! -e "$1" ]; then
        curl -skS "${CI_RUN:-http://mw-gitx.it}/shell/$1" >"/tmp/$1"
        chmod +x "/tmp/$1"
    fi
    # shellcheck disable=SC1090
    test "${2^^}" == "TRUE" && . "/tmp/$1"
    return 0
}

invoke() {
    arr=("$@")
    if test -e "/tmp/${arr[0]}"; then
        arr[0]="/tmp/${arr[0]}"
    elif test -e "/tmp/${arr[1]}"; then
        arr[1]="/tmp/${arr[1]}"
    fi
    echo "Executing ${arr[*]} ... " 1>&2
    "${arr[@]}"
}

test -e /root/.bashrc && . /root/.bashrc
test -e /root/.nvm/nvm.sh && . /root/.nvm/nvm.sh

test -z "${VERBOSE:-}${verbose:-}" || set -x

# <upgrade> <repository> <tag>
repository=$1
tag=$2
digest=$3
deliver=$4

if [[ "${CI_BUILD_REF_NAME}" =~ ^(main|master)$ ]] && [ "${ready^^}${READY^^}${Ready^^}" != "TRUE" ]; then
    exit 0
fi

chart="${repository#*/}"
IFS=/ read -r -a image <<< "${repository}"

# using @sha256 suffix as latest image
if test "${tag}" == "latest"; then
    echo "${digest}=>harbor"
    exit 0
fi

ns="develop"
if [[ "${CI_BUILD_REF_NAME}" =~ ^release.*$ ]] || [[ "${CI_BUILD_REF_NAME}" =~ ^hotfix.*$ ]]; then
    ns="test"
elif [[ "${CI_BUILD_REF_NAME}" =~ ^(main|master|v[0-9].*)$ ]]; then
    ns="prod"
fi

echo "Trying to upgrade [${chart}] in [${deliver}/${image[1]}/${image[2]}/${ns}/${tag}/${digest}] ... " 1>&2
curl -X POST "${deliver}/${image[1]}/${image[2]}/${ns}/${tag}/${digest}" 1>&2
